// 云函数入口文件
// wx-server-sdk本地调试
const cloud = require('wx-server-sdk')
const request = require('request-promise')
const tcbRouter = require('tcb-router')
cloud.init()
const BASE_URL = "http://www.hjmin.com"
// 云函数入口函数
exports.main = async (event, context) => {
  console.log(event);
  const app = new tcbRouter({
    event
  })
  // 获取数据库中数据并返回
  app.router('playList', async (ctx, next) => {
    ctx.body = await cloud.database()
      .collection('playList')
      .skip(event.start)
      .limit(event.count)
      .orderBy('createTime', 'desc')
      .get()
      .then(res => {
        return res.data
      })
  });
  // 获取歌曲信息
  app.router('musicList', async (ctx, next) => {
    ctx.body = await request(BASE_URL + '/playList/detail?id=' + event.playListId)
      .then(res => {
        console.log(res); //res是字符串需要转换
        return JSON.parse(res)
      })
      .catch(err => {
        console.log(err);
      })
  })
  // 获取歌曲地址
  app.router("musicUrl", async (ctx, next) => {
    // musicId
    ctx.body = await request(BASE_URL + '/song/url?id=' + event.musicId)
      .then(res=>{
        return JSON.parse(res).data[0];
      }).catch(err=>{
        console.log(err);
      })
  })
  return app.serve();
}